package com.ftg.learn.service.impl;

import com.ftg.learn.domain.SysDeptDomain;
import com.ftg.learn.mapper.SysDeptMapper;
import com.ftg.learn.service.SysDeptService;
import com.ftg.learn.util.ToWeb;
import com.ftg.learn.vo.OrgTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kangjx
 * @date 2024/2/20
 */
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Override
    public ToWeb<List<OrgTreeVo>> orgTree() {
        List<SysDeptDomain> sysDeptDomains = sysDeptMapper.orgTree();
        return ToWeb.success(getRoot(sysDeptDomains));
    }

    /**
     * 获取根节点
     * @param sysDeptDomains 部门列表
     * @return 根节点对象
     */
    private List<OrgTreeVo> getRoot(List<SysDeptDomain> sysDeptDomains){

        List<OrgTreeVo> trees = new ArrayList<>();

        for (SysDeptDomain sysDeptDomain : sysDeptDomains) {
            if (sysDeptDomain.getParentId() == null) {
                OrgTreeVo root = new OrgTreeVo();
                root.setId(sysDeptDomain.getId());
                root.setParent_id(sysDeptDomain.getParentId());
                root.setName(sysDeptDomain.getName());
                root.setDisabled(sysDeptDomain.getStatus() == 0);
                root.setChildren(new ArrayList<>());
                trees.add(root);
                /**
                 * 递归查找子节点
                 * @param sysDeptDomains 部门列表
                 * @param root 根节点对象
                 */
                findSon(sysDeptDomains,root);
            }
        }
        return trees;
    }



    /**
     * 递归查找子部门
     * @param sysDeptDomains 部门列表
     * @param current 当前部门
     */
    private void findSon(List<SysDeptDomain> sysDeptDomains, OrgTreeVo current){
        for (SysDeptDomain sysDeptDomain : sysDeptDomains) {
            if(sysDeptDomain.getParentId() == current.getId()){

                OrgTreeVo son = new OrgTreeVo();
                son.setId(sysDeptDomain.getId());
                son.setParent_id(sysDeptDomain.getParentId());
                son.setName(sysDeptDomain.getName());
                son.setDisabled(sysDeptDomain.getStatus() == 0);
                son.setChildren(new ArrayList<>());
                current.getChildren().add(son);

                findSon(sysDeptDomains, son); // 继续递归查找子部门

            }
        }
    }

}
